import React from "react";
//实现编程式跳转
import { Form, Input, Button, NavBar, Toast } from "antd-mobile";
import { LoginAPI } from "../pages/services/products";
import { useNavigate } from "react-router-dom";
function Login() {
  const navgite = useNavigate();
  const [myform] = Form.useForm();
  const back = () => {
    history.back();
  };
  return (
    <div>
      <div className="lgheader">
        <NavBar onBack={back}>登录</NavBar>
      </div>
      <Form
        layout="horizontal"
        form={myform}
        onFinish={async (v) => {
          await LoginAPI({ ...v }).then((res) => {
            console.log(res);
            if (res.success == true) {
              Toast.show({
                icon: "success",
                content: res.errorMessage,
                duration: 2000,
              });
              sessionStorage.setItem("token", res.data); //保存token值
              navgite("/user", { replace: true }); //跳转
            } else {
              Toast.show({
                icon: "fail",
                content: res.errorMessage,
                duration: 2000,
              });
            }
          });
        }}
        style={{ margin: "2rem 0" }}
      >
        <Form.Item
          label="用户名"
          name="userName"
          rules={[
            { required: true, message: "用户名不能为空" },
            {
              pattern: new RegExp(/^[0-9a-zA-Z_]{1,}$/, "g"),
              message: "名称只允许包含数字、字母和下划线",
            },
          ]}
        >
          <Input placeholder="请输入用户名" clearable />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input placeholder="请输入密码" clearable type="password" />
        </Form.Item>
        <Button
          shape="rounded"
          block
          color="primary"
          size="large"
          onClick={() => {
            myform.submit();
          }}
          style={{ marginTop: "2rem" }}
        >
          登录
        </Button>
      </Form>
      <div className="logbutton" style={{ display: "flex" }}>
        <i
          onClick={() => {
            console.log("1");
            navgite("/res", { replace: true });
          }}
        >
          新用户注册
        </i>
        <i>忘记密码</i>
      </div>
    </div>
  );
}

export default Login;
